<template>
    <div class="wrap-2 update_6p8_mobile_login update_6p8_mobile_app"  ref="ssoLogin">
        <van-dialog v-model="show" :title="statusTitle" confirmButtonColor="#075ebb" @cancel="$router.push({ path: '/loginIndex' })" class="login-alert"></van-dialog>
        <common-loading :isLoading="isLoading"></common-loading>
    </div>
</template>

<script>
import CommonLoading from '@/components/common/loading';
import Watermark from '@/libs/watermark.js';
import { clearLoginStorage } from '@/utils/tools';
export default {
    name: 'wx_login',
    components: {CommonLoading},
    data() {
        return {
            isLoading: true,
            statusTitle: '',
            show: false,
            code: null,
            state: '',
            openId: '',
            path: '/home',
            queryParams: {}, // 路由路径
            redirectKey: '' // 标记重定向key, redirect_path
        };
    },
    computed: {
    },
    methods: {
        login() {
            this.$axios({
                method: 'GET',
                url: '/app/api/user/wechat/login',
                params: {
                    code: this.code,
                    developer: 'mobile'
                }
            }).then(res => {
                this.isLoading = false;
                let data = res.data;
                let that = this;
                const sessionStorage = window.sessionStorage;
                sessionStorage.setItem('openid', data.result.openid);
                window.localStorage.removeItem('wizbank-user-auth');
                switch (data.code) {
                case 200: //登入成功
                    let localStorage = window.localStorage;
                    localStorage.setItem('token', data.result.token);
                    localStorage.setItem('loginUser', data.result.usrEntId);
                    that.$store.commit('setLoginUser', data.result.usrEntId);
                    that.$store.commit('setIsFirstLogin', parseInt(data.result.loginCredit) > 0);
                    that.$store.commit('setLoginCredit', parseInt(data.result.loginCredit));
                    that.$store.commit('setExternalStudent', data.result.externalStudent);
                    // 登陆成功获取水印
                    this.$axios({
                        method: 'GET',
                        url: '/app/api/system-setting/water-mark',
                        timeout: 1000,
                        headers: {
                            'Content-type': 'application/json'
                        }
                    }).then(res => {
                        let result = res;
                        let waterMark = result.data;
                        if (waterMark.value === 'ON') {
                            Watermark.set(data.result.userName);
                        }
                        window.localStorage.setItem('waterMarkSwitch', waterMark.value);
                    });
                    // 外部学员
                    if (data.result.externalStudent) {
                        that.$router.push({path: '/home/homeExter'});
                    } else {
                        //标记已跳转过目标地址
                        localStorage.setItem(this.redirectKey, 'true');
                        //如果已经绑定，直接跳转到首页
                        if (Object.keys(this.queryParams).length === 0) {
                            //如果没有参数直接跳转路由
                            this.$router.push({path: this.path});
                        } else {
                            //如果有参数跳转路由且携带参数
                            this.$router.push({path: this.path, query: this.queryParams});
                        }
                    }
                    break;
                case 500:
                    this.$router.push({ path: '/binging' });
                    break;
                default:
                    that.statusTitle = data.msg;
                    that.show = true;
                    break;
                }
            }).catch((e) => {
                this.statusTitle = this.$t('wechat_login_failed');
                this.show = true;
            });
        },
        getCode() {
            clearLoginStorage();
            // 二维码扫码标记
            let qrCodeMark = window.sessionStorage.getItem('qrcode_mark');
            // 清除sessionStorage
            window.sessionStorage.clear();
            if (qrCodeMark) {
                // 如果是通过二维码扫码进入的，重新设置二维码扫码标记
                window.sessionStorage.setItem('qrcode_mark', qrCodeMark);
            }
            Watermark.out(); // 清除用户水印
            if (this.code) {
                this.login(); //把code传给后台获取用户信息
            } else {
                // 请求获取微信授权
                this.$axios({
                    method: 'GET',
                    url: '/app/api/wechat/authorization/url',
                    params: {
                        path: this.state
                    }
                }).then(res => {
                    window.location.href = res.data.errMsg;
                }).catch((e) => {
                    this.statusTitle = this.$t('wechat_login_failed');
                    this.show = true;
                });
            }
        },
        /**
         * 获取地址栏的参数
         */
        getUrlParam() {
            let url = location.search;
            if (!url) {
                url = location.hash.replace('#', '');
            }
            if (url.indexOf('?') !== -1) {
                let str = url.split('?')[1];
                let urlParams = {};
                const params = str.split('&');
                for (let item of params) {
                    urlParams[item.split('=')[0]] = item.split('=')[1];
                }
                let openId = urlParams.code; // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
                let localStorage = window.localStorage;
                // 记录上一次openId
                let lastOpenId = localStorage.getItem('openId');
                if (openId === lastOpenId) {
                    this.code = null;
                    this.state = null;
                    localStorage.removeItem('openId');
                } else {
                    this.code = openId;
                    this.state = urlParams.state; // 获取微信授权之后重定向回来携带跳转的参数
                    localStorage.setItem('openId', openId);
                }
                this.resolveAddress(); // 获取跳转的地址
            } else {
                this.code = null;
                this.state = null;
                localStorage.removeItem('openId');
            }
        },
        /**
         * 解析地址栏的参数，获取跳转的路由地址及参数
         */
        resolveAddress() {
            if (this.state && this.state !== 'null') {
                // 标记是否已经跳转过目标地址的key
                this.redirectKey = 'redirect' + encodeURIComponent(this.state);
                const states = decodeURIComponent(this.state).split('?');
                this.path = states[0];
                if (states[1]) {
                    const params = states[1].split('&');
                    for (let param of params) {
                        this.queryParams[param.split('=')[0]] = param.split('=')[1];
                    }
                }
            }
        }
    },
    mounted() {
        this.$refs.ssoLogin.style.height = window.document.body.clientHeight + 'px';
        if (window.plus) {
            this.windowPlus = true;
        }
        new Promise((resolve, reject) => {
            this.getUrlParam();
            resolve();
        }).then(() => {
            this.getCode();
        });
    }
};
</script>

<style>

</style>
